package com.yisu.auction.api.web.controller;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.yisu.auction.api.core.service.*;
import com.yisu.auction.api.domain.request.BasePage;
import com.yisu.auction.api.domain.request.prizePackage.*;
import com.yisu.auction.api.domain.response.memberPackage.MineAuctionListResponse;
import com.yisu.auction.api.domain.response.memberPackage.MineCollectListResponse;
import com.yisu.auction.api.domain.response.prizePackage.*;
import com.yisu.auction.api.domain.vo.PrizePackageVos.HistoricalPrizes;
import com.yisu.auction.api.domain.vo.PrizePackageVos.HistoricalTendencyVo;
import com.yisu.auction.api.domain.vo.PrizePackageVos.PrizeInformationVo;
import com.yisu.auction.api.domain.vo.PrizePackageVos.ShowOrderListVo;
import com.yisu.auction.api.domain.vo.configJsonVos.CheckSwitchVo;
import com.yisu.auction.api.domain.vo.goodsInfoPackageVos.*;
import com.yisu.auction.api.domain.vo.indexPackageVos.MessageVo;
import com.yisu.auction.api.domain.vo.indexPackageVos.PrizeListVo;
import com.yisu.auction.api.domain.vo.indexPackageVos.SystemConfigVo;
import com.yisu.auction.api.web.interceptor.IAuthVerifyAnnotation;
import com.yisu.auction.ewf.common.enums.LoginTypeEnum;
import com.yisu.auction.ewf.common.enums.ResponseCode;
import com.yisu.auction.ewf.common.utils.DateUtil;
import com.yisu.auction.ewf.common.utils.StringUtil;
import com.yisu.auction.ewf.common.web.JsonResult;
import com.yisu.auction.ewf.entity.Prize;
import org.apache.calcite.linq4j.Linq4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * author: 赵杰
 * Business Description：竞品相关业务
 * createTime：2017/8/16
 */
@Controller
@RequestMapping(value = "/prize")
public class PrizeController extends BaseController {
    @Resource
    private IPersonageCollectService iPersonageCollectService;
    @Resource
    private IOfferPriceLogService iOfferPriceLogService;
    @Resource
    private IPrizeService iPrizeService;
    @Resource
    private IMessageService iMessageService;
    @Resource
    private IShowService iShowService;
    @Resource
    private IBalanceLogService iBalanceLogService;
    @Resource
    private IPrizeArchiveService iPrizeArchiveService;
    @Resource
    private ISystemConfigService iSystemConfigService;


    /**
     * 添加我的收藏
     *
     * @param personageCollectRequest 请求实体 含userToken,prizeId
     * @return
     */
    @RequestMapping(value = "/addMineCollect", method = {RequestMethod.POST}, produces = "application/json; charset=utf-8")
    @ResponseBody
    @IAuthVerifyAnnotation(Desc = "登录验证", LoginTypeEnum = LoginTypeEnum.NEED_LOGIN)
    public JsonResult addMineCollect(PersonageCollectRequest personageCollectRequest) {
        this.userToken = personageCollectRequest.getUserToken();
        personageCollectRequest.setMemberId(String.valueOf(this.getToken().getMemberId()));
        if (iPersonageCollectService.addMineCollect(personageCollectRequest)) {
            return new JsonResult(ResponseCode.SUCCESS.code, ResponseCode.SUCCESS.msg);
        }
        return new JsonResult(ResponseCode.FAILURE.code, ResponseCode.FAILURE.msg);
    }


    /**
     * author:黄萧林
     * Business Description:取消商品收藏
     *
     * @param cancelMineCollectRequest
     * @return
     */
    @RequestMapping(value = "/cancelMineCollect", method = {RequestMethod.POST}, produces = "application/json; charset=utf-8")
    @ResponseBody
    @IAuthVerifyAnnotation(Desc = "登录验证", LoginTypeEnum = LoginTypeEnum.NEED_LOGIN)
    public JsonResult cancelMineCollect(CancelMineCollectRequest cancelMineCollectRequest) {
        this.userToken = cancelMineCollectRequest.getUserToken();
        cancelMineCollectRequest.setMemberId(String.valueOf(this.getToken().getMemberId()));
        if (iPersonageCollectService.cancelMineCollect(cancelMineCollectRequest)) {
            return new JsonResult(ResponseCode.SUCCESS.code, ResponseCode.SUCCESS.msg);
        }
        return new JsonResult(ResponseCode.FAILURE.code, ResponseCode.FAILURE.msg);
    }

    /**
     * author:黄萧林
     * Business Description:获取收藏列表
     *
     * @param
     * @return
     */
    @RequestMapping(value = "/getMineCollectList", method = {RequestMethod.POST}, produces = "application/json; charset=utf-8")
    @ResponseBody
    @IAuthVerifyAnnotation(Desc = "登录验证", LoginTypeEnum = LoginTypeEnum.NEED_LOGIN)
    public JsonResult getMineCollectList(BasePage basePage) {
        this.userToken = basePage.getUserToken();
        basePage.setMemberId(String.valueOf(this.getToken().getMemberId()));
        JsonResult jsonResult = new JsonResult();
        MineCollectListResponse mineCollectListResponse = new MineCollectListResponse();
        List<PrizeListVo> prizeListVos = iPersonageCollectService.getMineCollectList(basePage);
        for (PrizeListVo item : prizeListVos) {
            if (!StringUtils.isEmpty(item.getImage())) {
                item.setImage(Linq4j.asEnumerable(item.getImage().split(",")).toList().get(0));
            }
            item.setCollectStatus(1);
        }
        mineCollectListResponse.setPrizeListVos(prizeListVos);
        jsonResult.setData(mineCollectListResponse);
        return jsonResult;
    }


    /**
     * author:黄萧林
     * Business Description:获取我的竞拍信息
     *
     * @param
     * @return
     */
    @RequestMapping(value = "/getMineAuctionList", method = {RequestMethod.POST}, produces = "application/json; charset=utf-8")
    @ResponseBody
    @IAuthVerifyAnnotation(Desc = "登录验证", LoginTypeEnum = LoginTypeEnum.NEED_LOGIN)
    public JsonResult getMineAuctionList(MineAuctionListRequest mineAuctionListRequest) throws Exception {
        this.userToken = mineAuctionListRequest.getUserToken();
        mineAuctionListRequest.setMemberId(String.valueOf(this.getToken().getMemberId()));
        JsonResult jsonResult = new JsonResult();
        MineAuctionListResponse mineAuctionListResponse = new MineAuctionListResponse();
        List<PrizeVo> prizeVos = iPrizeService.getMineAuctionList(mineAuctionListRequest);
        for (PrizeVo item : prizeVos) {
            if (!StringUtils.isEmpty(item.getImage())) {
                String[] imgArray = item.getImage().split(",");
                if (imgArray.length > 1) {
                    List<String> convertTemp = Lists.newArrayList(imgArray[0]);
                    item.setImage(StringUtils.join(convertTemp, ","));
                }
            }
        }
        if (!CollectionUtils.isEmpty(prizeVos)) {
            for (PrizeVo prizeVo : prizeVos) {
                ClosingBidRecordVo closingBidRecordVo = iOfferPriceLogService.getClosingBidRecordByPrizeId(prizeVo.getPrizeId());
                if (closingBidRecordVo != null) {
                    prizeVo.setNickname(closingBidRecordVo.getNickname());
                    prizeVo.setOfferPriceDate(simpleDateFormat.format(closingBidRecordVo.getOfferPriceDate()));
                    int second = 10 - (int) (DateUtil.diffValue(this.getDbDate(), closingBidRecordVo.getOfferPriceDate()) / 1000);
                    prizeVo.setBeginCountDown(second);
                }
                Long nextPeriodPrizeId = iPrizeService.getNextPeriodPrizeIdByPrizeId(prizeVo.getPrizeId());
                prizeVo.setNextPeriodPrizeId(nextPeriodPrizeId);
                //正在竞拍中的状态
                if (prizeVo.getStatus() < 3) {
                    //正在拍，时间显示正在拍
                    prizeVo.setAnnounceTime("正在参与竞拍");
                    prizeVo.setStatusDesc("进行中....");
                    prizeVo.setPrizeButtonVos(Lists.newArrayList(new PrizeButtonVo("继续竞拍", "treasurebox://ddbaoxiang.com/goodsDetail/" + prizeVo.getPrizeId())));
                }
                if (prizeVo.getStatus() >= 3) {
                    if (!org.apache.commons.lang3.StringUtils.isEmpty(prizeVo.getAnnounceTime())) {
                        prizeVo.setAnnounceTime(simpleDateFormat.format(simpleDateFormat.parse(prizeVo.getAnnounceTime())));
                    }
                    if ((prizeVo.getMemberId() + "").equals(mineAuctionListRequest.getMemberId())) {
                        if (prizeVo.getOrderStatus() == 0) {//等待付款
                            //查看用户此次购买总额
                            PrizeDetailRequest prizeDetailRequest = new PrizeDetailRequest();
                            prizeDetailRequest.setMemberId(mineAuctionListRequest.getMemberId());
                            prizeDetailRequest.setPrizeId(prizeVo.getPrizeId());
                            BigDecimal consumptionAmount = iOfferPriceLogService.getUserOfferPriceByPrizeId(prizeDetailRequest);
                            //剩余支付金额
                            BigDecimal payableAmount = prizeVo.getPrice().subtract(consumptionAmount);
                            prizeVo.setPayableAmount(payableAmount);
                            prizeVo.setStatusDesc("待付款....");
                            prizeVo.setPrizeButtonVos(Lists.newArrayList(new PrizeButtonVo("中奖详情", "treasurebox://ddbaoxiang.com/winningDetail/" + prizeVo.getPrizeId()),
                                    new PrizeButtonVo("去付款", "treasurebox://ddbaoxiang.com/buyPrize/" + prizeVo.getPrizeId() + "/" + prizeVo.getTransactionPrice())));
                        }
                        if (prizeVo.getOrderStatus() == 1) {//等待发货
                            prizeVo.setStatusDesc("待发货....");
                            prizeVo.setPrizeButtonVos(Lists.newArrayList(new PrizeButtonVo("中奖详情", "treasurebox://ddbaoxiang.com/winningDetail/" + prizeVo.getPrizeId())));
                        }
                        if (prizeVo.getOrderStatus() == 2) {//等待签收
                            prizeVo.setStatusDesc("待签收....");
                            prizeVo.setPrizeButtonVos(Lists.newArrayList(new PrizeButtonVo("中奖详情", "treasurebox://ddbaoxiang.com/winningDetail/" + prizeVo.getPrizeId()), new PrizeButtonVo("去签收", "treasurebox://ddbaoxiang.com/winningDetail/" + prizeVo.getPrizeId())));
                        }
                        if (prizeVo.getOrderStatus() == 3) {//等待签收
                            Prize checkModel = iPrizeService.getPrizeModelByPrizeId(prizeVo.getPrizeId());
                            if (checkModel.getShowOrderTime() == null) {
                                prizeVo.setStatusDesc("待晒单....");
                                prizeVo.setPrizeButtonVos(Lists.newArrayList(new PrizeButtonVo("中奖详情", "treasurebox://ddbaoxiang.com/winningDetail/" + prizeVo.getPrizeId()), new PrizeButtonVo("去晒单", "treasurebox://ddbaoxiang.com/shareMyPrize/" + prizeVo.getPrizeId() + "/" + prizeVo.getName())));
                            } else {
                                prizeVo.setPrizeButtonVos(Lists.newArrayList(new PrizeButtonVo("中奖详情", "treasurebox://ddbaoxiang.com/winningDetail/" + prizeVo.getPrizeId())));
                            }
                        }
                    } else {
                        BigDecimal returnMoney = iBalanceLogService.getReturnMoneyByPrizeId(prizeVo.getPrizeId());
                        prizeVo.setStatusDesc("");
                        if (returnMoney.intValue() != 0) {
                            prizeVo.setReturnMoneyDesc("已返" + returnMoney + "赠币");
                        }
                        prizeVo.setPrizeButtonVos(Lists.newArrayList(new PrizeButtonVo("再次购买", "treasurebox://ddbaoxiang.com/goodsDetail/" + prizeVo.getNextPeriodPrizeId())));
                    }
                    java.text.DecimalFormat df = new java.text.DecimalFormat("#.00");
                    float subtract = (prizeVo.getPrice().subtract(prizeVo.getTransactionPrice())).floatValue();
                    double savePercentage = Double.parseDouble(df.format(((subtract) / prizeVo.getPrice().floatValue()) * 100));
                    prizeVo.setSavePercentage(String.valueOf(savePercentage) + "%");
                }
            }
        }
        mineAuctionListResponse.setPrizeVos(prizeVos);
        jsonResult.setData(mineAuctionListResponse);
        return jsonResult;
    }

    /**
     * author:黄萧林
     * Business Description:获取历史走势列表数据
     *
     * @param
     * @return
     */
    @RequestMapping(value = "/getHistoricalTendencyListByPrizeId", method = {RequestMethod.POST}, produces = "application/json; charset=utf-8")
    @ResponseBody
    @IAuthVerifyAnnotation(Desc = "登录验证", LoginTypeEnum = LoginTypeEnum.NO_NEED_LOGIN)
    public JsonResult getHistoricalTendencyListByPrizeId(HistoricalTendencyRequest historicalTendencyRequest) {
        this.userToken = historicalTendencyRequest.getUserToken();
        historicalTendencyRequest.setMemberId(String.valueOf(this.getToken().getMemberId()));
        JsonResult jsonResult = new JsonResult();
        HistoricalTendencyResponse historicalTendencyResponse = new HistoricalTendencyResponse();
        PrizeInformationVo prizeInformationVo = iPrizeService.getPrizeInfo(historicalTendencyRequest);
        List<HistoricalTendencyVo> historicalTendencyVos = iPrizeService.getHistoricalTendencyListByPrizeId(historicalTendencyRequest);
        List<HistoricalPrizes> historicalPrizesList = new ArrayList<>();
        for (HistoricalTendencyVo item : historicalTendencyVos) {
            HistoricalPrizes historicalPrizes = new HistoricalPrizes();
            historicalPrizes.setTerm(item.getTerm());
            historicalPrizes.setAveragePrice(item.getAveragePrice());
            historicalPrizes.setTransactionPrice(item.getTransactionPrice());
            historicalPrizesList.add(historicalPrizes);
        }
        historicalTendencyResponse.setInformationVo(prizeInformationVo);
        historicalTendencyResponse.setHistoricalPrizes(historicalPrizesList);
        historicalTendencyResponse.setHistoricalTendencyVos(historicalTendencyVos);
        jsonResult.setData(historicalTendencyResponse);
        return jsonResult;
    }


    /**
     * author: 赵杰
     * Business Description：获取出价记录
     *
     * @param
     * @return 系统参数
     */
    @RequestMapping(value = "/getOfferPriceList", method = {RequestMethod.POST}, produces = "application/json; charset=utf-8")
    @ResponseBody
    @IAuthVerifyAnnotation(Desc = "登录验证", LoginTypeEnum = LoginTypeEnum.NO_NEED_LOGIN)
    public JsonResult getOfferPriceList(PrizeDetailRequest prizeDetailRequest) throws ParseException {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        OfferPriceListResponse offerPriceListResponse = new OfferPriceListResponse();
        if (prizeDetailRequest.getPageindex() == 1) {
            prizeDetailRequest.setCurrentSystemTime("");
        } else {
            prizeDetailRequest.setCurrentSystemTime(prizeDetailRequest.getCurrentSystemTime());
        }
        List<OfferPriceVo> offerPriceVos = iOfferPriceLogService.getOfferPriceLogListByPrizeId(prizeDetailRequest);
        if (!CollectionUtils.isEmpty(offerPriceVos)) {
            Prize prizeVo = iPrizeService.getPrizeModelByPrizeId(prizeDetailRequest.getPrizeId());
            for (OfferPriceVo item : offerPriceVos) {
                if (item.getTransactionPrice() == offerPriceVos.get(0).getTransactionPrice()) {
                    item.setAuctionStatus("拍中");
                    if (prizeVo.getStatus() == 1) {
                        item.setAuctionStatus("待定");
                    }
                } else {
                    item.setAuctionStatus("出局");
                }
            }
        }
        if (prizeDetailRequest.getPageindex() == 1) {
            Date now = new Date();
            offerPriceListResponse.setCurrentSystemTime(simpleDateFormat.format(now));
        } else {
            offerPriceListResponse.setCurrentSystemTime(prizeDetailRequest.getCurrentSystemTime());
        }
        offerPriceListResponse.setOfferPriceVos(offerPriceVos);
        return new JsonResult(offerPriceListResponse);
    }

    /**
     * author: 赵杰
     * Business Description：获取竞品详情业务
     *
     * @param
     * @return 系统参数
     */
    @RequestMapping(value = "/getPrizeDetailInfo", method = {RequestMethod.POST}, produces = "application/json; charset=utf-8")
    @ResponseBody
    @IAuthVerifyAnnotation(Desc = "登录验证", LoginTypeEnum = LoginTypeEnum.NO_NEED_LOGIN)
    public JsonResult getPrizeDetailInfo(PrizeDetailRequest prizeDetailRequest) {
        JsonResult jsonResult = new JsonResult();
        PrizeDetailResponse prizeDetailResponse = new PrizeDetailResponse();
        try {
            PrizeVo prizeVo = iPrizeService.getPrizeDetailByPrizeId(prizeDetailRequest);
            if (!StringUtils.isEmpty(prizeDetailRequest.getUserToken())) {
                this.userToken = prizeDetailRequest.getUserToken();
                prizeDetailRequest.setMemberId(String.valueOf(this.getToken().getMemberId()));
                BigDecimal consumptionWallet = iOfferPriceLogService.getUserOfferPriceByPrizeId(prizeDetailRequest);
                //个人累计投注金额
                prizeVo.setConsumptionWallet(consumptionWallet != null ? consumptionWallet : new BigDecimal(0));
            }
            //获取最后下注时间及开始倒计时秒数
            ClosingBidRecordVo closingBidRecordVo = iOfferPriceLogService.getClosingBidRecordByPrizeId(prizeVo.getPrizeId());
            if (closingBidRecordVo != null) {
                prizeVo.setOfferPriceDate(simpleDateFormat.format(closingBidRecordVo.getOfferPriceDate()));
                int second = 10 - (int) (DateUtil.diffValue(this.getDbDate(), closingBidRecordVo.getOfferPriceDate()) / 1000);
                prizeVo.setBeginCountDown(second);
            }
            Long nextPeriodPrizeId = iPrizeService.getNextPeriodPrizeIdByPrizeId(prizeVo.getPrizeId());
            prizeVo.setNextPeriodPrizeId(nextPeriodPrizeId);
            if (!this.getAllowAuction()) {
                prizeVo.setStatus((byte) -100);
            }
            prizeDetailResponse.setPrizeVo(prizeVo);
            prizeDetailRequest.setPageindex(1);
            prizeDetailRequest.setPagesize(3);
            List<OfferPriceVo> offerPriceVos = iOfferPriceLogService.getOfferPriceLogListByPrizeId(prizeDetailRequest);
            if (!CollectionUtils.isEmpty(offerPriceVos)) {
                for (OfferPriceVo item : offerPriceVos) {
                    if (item.getTransactionPrice() == offerPriceVos.get(0).getTransactionPrice()) {
                        item.setAuctionStatus("拍中");
                        if (prizeVo.getStatus() == 1) {
                            item.setAuctionStatus("待定");
                        }
                    } else {
                        item.setAuctionStatus("出局");
                    }
                }
            }
            prizeDetailResponse.setOfferPriceVos(offerPriceVos);
            AuctionDescribeVo auctionDescribeVo = new AuctionDescribeVo();
            List<String> titles = Lists.newArrayList("零风险", "正品承诺", "极速发货", "公平公正");
            auctionDescribeVo.setTitles(titles);
            List<String> auctionDescribes = Lists.newArrayList();
            auctionDescribes.add("起拍价|¥0.00");
            auctionDescribes.add("手续费|1拍币/1次");
            auctionDescribes.add("差价购买|敬请期待");
            auctionDescribes.add("加价幅度|¥0.1");
            auctionDescribes.add("竞拍倒计时|10s");
            auctionDescribes.add("退币比例|30%");
            auctionDescribeVo.setAuctionDescribes(auctionDescribes);
            prizeDetailResponse.setAuctionDescribeVo(auctionDescribeVo);
            //晒单列表
            prizeDetailRequest.setPageindex(1);
            prizeDetailRequest.setPagesize(10);
            List<ShowOrderListVo> showOrderListVos = iShowService.getShowOrderList(prizeDetailRequest);
            prizeDetailResponse.setShowOrderListVos(showOrderListVos);
        } catch (Exception e) {
            logger.error("获取竞品详情业务异常：" + e.getMessage());
        }
        jsonResult.setData(prizeDetailResponse);
        return jsonResult;
    }


    /**
     * author: 赵杰
     * Business Description：获取往期记录-通过prizeId
     *
     * @param
     * @return 系统参数
     */
    @RequestMapping(value = "/getPreviousRecord", method = {RequestMethod.POST}, produces = "application/json; charset=utf-8")
    @ResponseBody
    @IAuthVerifyAnnotation(Desc = "登录验证", LoginTypeEnum = LoginTypeEnum.NO_NEED_LOGIN)
    public JsonResult getPreviousRecord(PreviousRecordRequest previousRecordRequest) {
        JsonResult jsonResult = new JsonResult();
        PreviousRecordResponse previousRecordResponse = new PreviousRecordResponse();
        try {
            List<PreviousRecordVo> previousRecordVos = iPrizeService.getPreviousRecordListByPrizeId(previousRecordRequest);
            if (previousRecordVos == null)
                previousRecordVos = Lists.newArrayList();
            Integer totalPage = previousRecordRequest.getPagesize();
            Integer surplusPageSize = previousRecordRequest.getPagesize();
            if (!CollectionUtils.isEmpty(previousRecordVos)) {
                surplusPageSize = totalPage - previousRecordVos.size();
            }
            if (surplusPageSize > 0) {
                if (surplusPageSize != previousRecordRequest.getPagesize()) {
                    previousRecordRequest.setPageindex(1);
                }
                List<PreviousRecordVo> replenishList = iPrizeArchiveService.getPreviousRecordListByPrizeId(previousRecordRequest);
                if (!CollectionUtils.isEmpty(replenishList)) {
                    for (PreviousRecordVo item : replenishList) {
                        previousRecordVos.add(item);
                    }
                }
            }
            if (!CollectionUtils.isEmpty(previousRecordVos)) {
                for (PreviousRecordVo item : previousRecordVos) {
                    java.text.DecimalFormat df = new java.text.DecimalFormat("#.00");
                    float subtract = (item.getPrice().subtract(item.getTransactionPrice())).floatValue();
                    double savePercentage = Double.parseDouble(df.format(((subtract) / item.getPrice().floatValue()) * 100));
                    item.setSavePercentage(String.valueOf(savePercentage) + "%");
                }
            }
            previousRecordResponse.setPreviousRecordVos(previousRecordVos);
        } catch (Exception e) {
            logger.error("获取往期记录异常：" + e.getMessage());
        }
        jsonResult.setData(previousRecordResponse);
        return jsonResult;
    }


    /**
     * author: 赵杰
     * Business Description：获取近期揭晓列表
     *
     * @param
     * @return 系统参数
     */
    @RequestMapping(value = "/getLatestAnnouncedList", method = {RequestMethod.POST}, produces = "application/json; charset=utf-8")
    @ResponseBody
    @IAuthVerifyAnnotation(Desc = "登录验证", LoginTypeEnum = LoginTypeEnum.NO_NEED_LOGIN)
    public JsonResult getLatestAnnouncedList(LatestAnnouncedRequest latestAnnouncedRequest) {
        JsonResult jsonResult = new JsonResult();
        LatestAnnouncedResponse latestAnnouncedResponse = new LatestAnnouncedResponse();
        try {
            //拍卖头条跑马灯业务
            List<MessageVo> messageVos = Lists.newArrayList();
            if (latestAnnouncedRequest.getPageindex() == 1) {
                //当加载第一页的时候返回拍卖头条，其他的不执行，返回空
                messageVos = iMessageService.getFrontPageList();
            }
            latestAnnouncedResponse.setMessageVos(messageVos);
            Integer totalPage = latestAnnouncedRequest.getPagesize();
            Integer surplusPageSize = latestAnnouncedRequest.getPagesize();
            List<LatestAnnouncedVo> latestAnnouncedVos = iPrizeService.getLatestAnnouncedList(latestAnnouncedRequest);
            if (latestAnnouncedVos == null)
                latestAnnouncedVos = Lists.newArrayList();
            if (!CollectionUtils.isEmpty(latestAnnouncedVos)) {
                surplusPageSize = totalPage - latestAnnouncedVos.size();
            }
            if (surplusPageSize > 0) {
                if (surplusPageSize != latestAnnouncedRequest.getPagesize()) {
                    latestAnnouncedRequest.setPageindex(1);
                }
                List<LatestAnnouncedVo> replenishList = iPrizeArchiveService.getLatestAnnouncedList(latestAnnouncedRequest);
                if (!CollectionUtils.isEmpty(replenishList)) {
                    for (LatestAnnouncedVo item : replenishList) {
                        latestAnnouncedVos.add(item);
                    }
                }
            }
            if (!CollectionUtils.isEmpty(latestAnnouncedVos)) {
                for (LatestAnnouncedVo item : latestAnnouncedVos) {
                    item.setImage(item.getImage() != null ? item.getImage().split(",")[0] : "");
                    java.text.DecimalFormat df = new java.text.DecimalFormat("#.00");
                    float subtract = (item.getPrice().subtract(item.getTransactionPrice())).floatValue();
                    double savePercentage = Double.parseDouble(df.format(((subtract) / item.getPrice().floatValue()) * 100));
                    item.setSavePercentage(String.valueOf(savePercentage) + "%");
                    Long nextPeriodPrizeId = iPrizeService.getNextPeriodPrizeIdByPrizeId(item.getPrizeId());
                    item.setNextPeriodPrizeId(nextPeriodPrizeId);
                }
            }
            latestAnnouncedResponse.setLatestAnnouncedVos(latestAnnouncedVos);
        } catch (Exception e) {
            logger.error("获取近期揭晓列表异常：" + e.getMessage());
        }
        jsonResult.setData(latestAnnouncedResponse);
        return jsonResult;
    }


    /**
     * author: 赵杰
     * Business Description：获取全部商品列表
     *
     * @param
     * @return 系统参数
     */
    @RequestMapping(value = "/getAllPrizeList", method = {RequestMethod.POST}, produces = "application/json; charset=utf-8")
    @ResponseBody
    @IAuthVerifyAnnotation(Desc = "登录验证", LoginTypeEnum = LoginTypeEnum.NO_NEED_LOGIN)
    public JsonResult getAllPrizeList(PrizeListRequest prizeListRequest) {
        JsonResult jsonResult = new JsonResult();
        AllPrizeListResponse allPrizeListResponse = new AllPrizeListResponse();
        try {
            List<PrizeListVo> prizeListVos = Lists.newArrayList();
            GoodsTypeRequest goodsTypeRequest=new GoodsTypeRequest();
            goodsTypeRequest.setAppSign(prizeListRequest.getAppSign());
            List<GoodsTypeVo> goodsTypeVos = iPrizeService.getGoodsTypeList(goodsTypeRequest);
            if (!CollectionUtils.isEmpty(goodsTypeVos) && goodsTypeVos.size() > 0) {
                long goodsTypeId = goodsTypeVos.get(0).getGoodsTypeId();
                prizeListRequest.setGoodsTypeId(goodsTypeId);
                prizeListRequest.setPageindex(1);
                prizeListRequest.setPagesize(20);
                prizeListVos = iPrizeService.getPrizeListByGoodsTypeId(prizeListRequest);
                if (!CollectionUtils.isEmpty(prizeListVos)) {
                    for (PrizeListVo prizeListVo : prizeListVos) {
                        prizeListVo = supplementModel(prizeListVo);
                        if (!StringUtils.isEmpty(prizeListVo.getImage())) {
                            prizeListVo.setImage(Linq4j.asEnumerable(prizeListVo.getImage().split(",")).toList().get(0));
                        }
                        if (!this.getAllowAuction()) {
                            prizeListVo.setStatus(-100);
                        }
                    }
                }
            }
            allPrizeListResponse.setGoodsTypeVos(goodsTypeVos);
            allPrizeListResponse.setPrizeListVos(prizeListVos);
        } catch (Exception e) {
            logger.error("获取全部商品列表异常：" + e.getMessage());
        }
        jsonResult.setData(allPrizeListResponse);
        return jsonResult;
    }

    protected PrizeListVo supplementModel(PrizeListVo prizeListVo) throws Exception {
        if (prizeListVo != null) {
            ClosingBidRecordVo closingBidRecordVo = iOfferPriceLogService.getClosingBidRecordByPrizeId(prizeListVo.getPrizeId());
            if (closingBidRecordVo != null) {
                prizeListVo.setNickname(closingBidRecordVo.getNickname());
                prizeListVo.setIco(closingBidRecordVo.getIco());
                prizeListVo.setOfferPriceDate(simpleDateFormat.format(closingBidRecordVo.getOfferPriceDate()));
                int second = 10 - (int) (DateUtil.diffValue(this.getDbDate(), closingBidRecordVo.getOfferPriceDate()) / 1000);
                prizeListVo.setBeginCountDown(second);
            }
            Long nextPeriodPrizeId = iPrizeService.getNextPeriodPrizeIdByPrizeId(prizeListVo.getPrizeId());
            prizeListVo.setNextPeriodPrizeId(nextPeriodPrizeId);
        }
        return prizeListVo;
    }


    /**
     * author: 赵杰
     * Business Description：通过商品类目ID获取竞品列表
     *
     * @param
     * @return 系统参数
     */
    @RequestMapping(value = "/getPrizeListByGoodsTypeId", method = {RequestMethod.POST}, produces = "application/json; charset=utf-8")
    @ResponseBody
    @IAuthVerifyAnnotation(Desc = "登录验证", LoginTypeEnum = LoginTypeEnum.NO_NEED_LOGIN)
    public JsonResult getPrizeListByGoodsTypeId(PrizeListRequest prizeListRequest) {
        JsonResult jsonResult = new JsonResult();
        PrizeListResponse PrizeListResponse = new PrizeListResponse();
        try {
            List<PrizeListVo> prizeListVos = Lists.newArrayList();
            prizeListVos = iPrizeService.getPrizeListByGoodsTypeId(prizeListRequest);
            if (!CollectionUtils.isEmpty(prizeListVos)) {
                for (PrizeListVo prizeListVo : prizeListVos) {
                    prizeListVo = supplementModel(prizeListVo);
                    if (!this.getAllowAuction()) {
                        prizeListVo.setStatus(-100);
                    }
                    if (!StringUtils.isEmpty(prizeListVo.getImage())) {
                        prizeListVo.setImage(Linq4j.asEnumerable(prizeListVo.getImage().split(",")).toList().get(0));
                    }
                }
            }
            PrizeListResponse.setPrizeListVos(prizeListVos);
        } catch (Exception e) {
            logger.error("通过商品类目ID获取竞品列表：" + e.getMessage());
        }
        jsonResult.setData(PrizeListResponse);
        return jsonResult;
    }


    /**
     * author: 赵杰
     * Business Description：每秒刷新最新竞拍接口，详情专用
     *
     * @param
     * @return 系统参数
     */
    @RequestMapping(value = "/getAuctionResult", method = {RequestMethod.POST}, produces = "application/json; charset=utf-8")
    @ResponseBody
    @IAuthVerifyAnnotation(Desc = "登录验证", LoginTypeEnum = LoginTypeEnum.NO_NEED_LOGIN)
    public JsonResult getAuctionResult(PrizeDetailRequest prizeDetailRequest) throws Exception {
        JsonResult jsonResult = new JsonResult();
        AuctionResultResponse auctionResultResponse = new AuctionResultResponse();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        AuctionResultVo auctionResultVo = iPrizeService.getAuctionResultByPrizeId(prizeDetailRequest.getPrizeId());
        if (auctionResultVo != null) {
            if (!this.getAllowAuction()) {
                auctionResultVo.setStatus(-100);
            }
            ClosingBidRecordVo closingBidRecordVo = iOfferPriceLogService.getClosingBidRecordByPrizeId(auctionResultVo.getPrizeId());
            if (closingBidRecordVo != null) {
                auctionResultVo.setIco(closingBidRecordVo.getIco());
                auctionResultVo.setNickname(closingBidRecordVo.getNickname());
                auctionResultVo.setOfferPriceDate(simpleDateFormat.format(closingBidRecordVo.getOfferPriceDate()));
                int second = 10 - (int) (DateUtil.diffValue(this.getDbDate(), closingBidRecordVo.getOfferPriceDate()) / 1000);
                auctionResultVo.setBeginCountDown(second);
            }
        }
        prizeDetailRequest.setPageindex(1);
        prizeDetailRequest.setPagesize(3);
        List<OfferPriceVo> offerPriceVos = iOfferPriceLogService.getOfferPriceLogListByPrizeId(prizeDetailRequest);
        if (!CollectionUtils.isEmpty(offerPriceVos)) {
            Prize prizeVo = iPrizeService.getPrizeModelByPrizeId(prizeDetailRequest.getPrizeId());
            for (OfferPriceVo item : offerPriceVos) {
                if (item.getTransactionPrice() == offerPriceVos.get(0).getTransactionPrice()) {
                    item.setAuctionStatus("拍中");
                    if (prizeVo.getStatus() == 1) {
                        item.setAuctionStatus("待定");
                    }
                } else {
                    item.setAuctionStatus("出局");
                }
            }
            auctionResultVo.setOfferPriceVos(offerPriceVos);
        }
        auctionResultResponse.setAuctionResultVo(auctionResultVo);
        jsonResult.setData(auctionResultResponse);
        return jsonResult;
    }


    /**
     * author: 赵杰
     * Business Description：每秒刷新最新竞拍接口，列表专用
     *
     * @param
     * @return 系统参数
     */
    @RequestMapping(value = "/getAuctionResultForIndex", method = {RequestMethod.POST}, produces = "application/json; charset=utf-8")
    @ResponseBody
    @IAuthVerifyAnnotation(Desc = "登录验证", LoginTypeEnum = LoginTypeEnum.NO_NEED_LOGIN)
    public JsonResult getAuctionResultForIndex(PrizeDetailRequest prizeDetailRequest) throws Exception {
        JsonResult jsonResult = new JsonResult();
        AuctionResultForIndexResponse auctionResultForIndexResponse = new AuctionResultForIndexResponse();
        PrizeListVo prizeListVo = new PrizeListVo();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        AuctionResultVo auctionResultVo = iPrizeService.getAuctionResultByPrizeId(prizeDetailRequest.getPrizeId());
        Prize prize = iPrizeService.getPrizeModelByPrizeId(prizeDetailRequest.getPrizeId());
        if (prize != null) {
            prizeListVo.setPrizeId(prize.getId());
            prizeListVo.setName(prize.getName());
            prizeListVo.setPrice(prize.getPrice());
            if (!StringUtils.isEmpty(prize.getImage())) {
                prizeListVo.setImage(Linq4j.asEnumerable(prize.getImage().split(",")).toList().get(0));
            }
            prizeListVo.setIsTen(prize.getIsTen());
            prizeListVo.setTerm(prize.getTerm());
            prizeListVo.setStatus(Integer.valueOf(prize.getStatus()));
            if (!this.getAllowAuction()) {
                prizeListVo.setStatus(-100);
            }
            ClosingBidRecordVo closingBidRecordVo = iOfferPriceLogService.getClosingBidRecordByPrizeId(auctionResultVo.getPrizeId());
            if (closingBidRecordVo != null) {
                prizeListVo.setNickname(closingBidRecordVo.getNickname());
                prizeListVo.setTransactionPrice(auctionResultVo.getTransactionPrice());
                prizeListVo.setOfferPriceDate(simpleDateFormat.format(closingBidRecordVo.getOfferPriceDate()));
                int second = 10 - (int) (DateUtil.diffValue(this.getDbDate(), closingBidRecordVo.getOfferPriceDate()) / 1000);
                prizeListVo.setBeginCountDown(second);
            }
            prizeListVo.setCollectStatus(0);
            if (!StringUtils.isEmpty(prizeDetailRequest.getUserToken())) {
                this.userToken = prizeDetailRequest.getUserToken();
                prizeDetailRequest.setMemberId(String.valueOf(this.getToken().getMemberId()));
                PersonageCollectRequest personageCollectRequest = new PersonageCollectRequest();
                personageCollectRequest.setMemberId(prizeDetailRequest.getMemberId());
                personageCollectRequest.setPrizeId(Integer.parseInt(String.valueOf(prizeDetailRequest.getPrizeId())));
                if (iPersonageCollectService.collectStatus(personageCollectRequest))
                    prizeListVo.setCollectStatus(1);
            }
            Long nextPeriodPrizeId = iPrizeService.getNextPeriodPrizeIdByPrizeId(prizeListVo.getPrizeId());
            prizeListVo.setNextPeriodPrizeId(nextPeriodPrizeId);
        }
        auctionResultForIndexResponse.setPrizeListVo(prizeListVo);
        jsonResult.setData(auctionResultForIndexResponse);
        return jsonResult;
    }

    /**
     * author: 赵杰
     * Business Description：确认收货
     *
     * @param
     * @return 系统参数
     */
    @RequestMapping(value = "/confirmReceipt", method = {RequestMethod.POST}, produces = "application/json; charset=utf-8")
    @ResponseBody
    @IAuthVerifyAnnotation(Desc = "登录验证", LoginTypeEnum = LoginTypeEnum.NEED_LOGIN)
    public JsonResult confirmReceipt(PrizeDetailRequest prizeDetailRequest) throws Exception {
        Prize prize = iPrizeService.getPrizeModelByPrizeId(prizeDetailRequest.getPrizeId());
        if (prize == null) {
            return new JsonResult(-1, "非法请求");
        }
        Prize updatePrize = new Prize();
        updatePrize.setId(prize.getId());
        updatePrize.setConfirmTime(new Date());
        updatePrize.setOrderStatus(3);//收货
        if (iPrizeService.updatePrizeSelective(updatePrize)) {
            return new JsonResult(ResponseCode.SUCCESS.code, "操作成功");
        }
        return new JsonResult(ResponseCode.FAILURE.code, "操作失败");
    }

    /**
     * author: 赵杰
     * Business Description：绑定收货地址
     *
     * @param
     * @return 系统参数
     */
    @RequestMapping(value = "/bandingAddress", method = {RequestMethod.POST}, produces = "application/json; charset=utf-8")
    @ResponseBody
    @IAuthVerifyAnnotation(Desc = "登录验证", LoginTypeEnum = LoginTypeEnum.NEED_LOGIN)
    public JsonResult bandingAddress(PrizeDetailRequest prizeDetailRequest) throws Exception {
        if (iPrizeService.bandingAddress(prizeDetailRequest.getPrizeId(), prizeDetailRequest.getAddressId())) {
            return new JsonResult(ResponseCode.SUCCESS.code, "操作成功");
        }
        return new JsonResult(ResponseCode.FAILURE.code, "操作失败");
    }

}
